import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_demo/http/api.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

class PhotosPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _PhotosPageState();
}

class _PhotosPageState extends State<PhotosPage> {
  final ScrollController _scrollController = ScrollController();
  bool _isLoadPage = true;
  bool _isLoadMore = false;
  final List _photos = [];
  var _curPage = 1;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      var maxScroll = _scrollController.position.maxScrollExtent;
      var pixels = _scrollController.position.pixels;
      if (maxScroll == pixels) _loadMorePhotos();
    });
    _reloadPhotos();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Offstage(
          offstage: !_isLoadPage,
          child: const Center(child: CircularProgressIndicator()),
        ),
        Column(
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            Expanded(
              child: Offstage(
                offstage: _isLoadPage,
                child: RefreshIndicator(
                    child: StaggeredGridView.countBuilder(
                      shrinkWrap: true,
                      crossAxisCount: 4,
                      itemCount: _photos.length,
                      itemBuilder: (context, index) => _buildItem(index),
                      staggeredTileBuilder: (index) => const StaggeredTile.fit(2),
                      controller: _scrollController,
                    ),
                    onRefresh: _reloadPhotos
                ),
              ),
              flex: 1,
            ),
            Offstage(
              offstage: !_isLoadMore,
              child: Center(
                child: Container(
                  child: Row(
                    children: <Widget>[
                      Expanded(
                        child: Container(
                          child: const SizedBox(
                            child: CircularProgressIndicator(
                              strokeWidth: 2,
                            ),
                            width: 14,
                            height: 14,
                          ),
                          alignment: Alignment.centerRight,
                          margin: const EdgeInsets.only(right: 10),
                        ),
                      ),
                      const Expanded(
                        child: Text("加载更多..."),
                      )
                    ],
                  ),
                  padding: const EdgeInsets.all(15),
                ),
              ),
            ),
          ],
        ),
      ],
    );
  }

  _getPhotos(int page) async {
    var data = await PicsumPhotosApi.getImages(page);
    if (data != null) {
      setState(() {
        if (_curPage == 1) _photos.clear();
        _photos.addAll(data);
      });
    }
  }

  Future<void> _reloadPhotos() async {
    setState(() {
      _isLoadPage = false;
    });
    await _getPhotos(_curPage = 1);
  }

  _loadMorePhotos() async {
    setState(() {
      _isLoadMore = true;
    });
    await _getPhotos(++_curPage);
    setState(() {
      _isLoadMore = false;
    });
  }

  _buildItem(int index) {
    var photo = _photos[index];
    return PhotoItem(photo);
  }
}

class PhotoItem extends StatelessWidget {
  final dynamic _photo;
  late num _imageWidth;
  late num _imageHeight;

  PhotoItem(this._photo, {Key? key}) : super(key: key) {
    _imageWidth = (ScreenUtil().screenWidth - 10) / 2;
    _imageHeight = _imageWidth / (_photo["width"] / _photo["height"]);
  }

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 4.0,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          FadeInImage.assetNetwork(
            placeholder: "assets/loading.svg",
            placeholderFit: BoxFit.none,
            image: _photo["download_url"],
            width: _imageWidth.toDouble(),
            height: _imageHeight.toDouble(),
            imageCacheWidth: _imageWidth.toInt(),
            imageCacheHeight: _imageHeight.toInt(),
            fit: BoxFit.fill,
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Text(
              _photo["author"],
              overflow: TextOverflow.ellipsis,
              style: const TextStyle(
                color: Colors.black,
                fontWeight: FontWeight.w700,
                fontSize: 16,
              ),
              maxLines: 2,
            ),
          ),
        ],
      ),
    );
  }
}